
package com.badlogic.androidgames.asyncutil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.badlogic.androidgames.framework.impl.GLGame;
import com.badlogic.androidgames.util.Result;
import com.badlogic.androidgames.util.Result.ResourceType;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;


public class AsyncResourceLoading extends AsyncTask<Integer, Integer, Long> 
{
	public Result[] result;
	public Bitmap[] bitmap;

	GLGame g;
	ProgressDialog progressBar;
	Integer idR;
	String param;

	public AsyncResourceLoading(GLGame g, String param)
	{
		super();
		this.g = g;
		this.param = param;
		
		result = new Result[1];
		bitmap = new Bitmap[1];
	}

	protected Long doInBackground(Integer... idRicerca) {
		publishProgress(1);

		idR = idRicerca[0];
		//gestione ricerca su flickr
		if(idRicerca[0] == 2)
		{
			try {
				String apiKey = "f435cdf8fcae4c89b0d0a4be1d055909";
				URL urlFlickr;
				
				urlFlickr = new URL("http://api.flickr.com/services/rest/"+
						"?method=flickr.photos.getInfo"+
						"&api_key=" + apiKey + "&photo_id="+ param+ "&format=json");
				
				URLConnection connection = urlFlickr.openConnection();
				String line;
				StringBuilder builder = new StringBuilder();
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}

				int start = builder.toString().indexOf("(") + 1;
				int end = builder.toString().length() - 1;
				String jSONString = builder.toString().substring( start, end);
				//after cutting off the junk, its ok

				JSONObject jSONObject = new JSONObject(jSONString); //whole json object

				JSONObject photo = jSONObject.getJSONObject("photo");
				String FARMID = "1";//photo.getString("farm");
				String SERVERID = photo.getString("server");
				String OWNER = photo.getJSONObject("owner").getString("nsid");
				String userName = photo.getJSONObject("owner").getString("username");
				String SECRET = photo.getString("secret");
				String ID = photo.getString("id");
				String tit = photo.getString("title");

				StringBuilder sb = new StringBuilder();

				sb.append("http://farm");
				sb.append(FARMID);
				sb.append(".static.flickr.com/");
				sb.append(SERVERID);
				sb.append("/");
				sb.append(ID);
				sb.append("_");
				sb.append(SECRET);
				sb.append("_s");                    
				sb.append(".jpg");

				URL imgFlickr = new URL(sb.toString());

				StringBuilder sbL = new StringBuilder();

				sbL.append("http://farm");
				sbL.append(FARMID);
				sbL.append(".static.flickr.com/");
				sbL.append(SERVERID);
				sbL.append("/");
				sbL.append(ID);
				sbL.append("_");
				sbL.append(SECRET);
				sbL.append("_z");                    
				sbL.append(".jpg");

				InputStream in = imgFlickr.openConnection().getInputStream();

				bitmap[0] = BitmapFactory.decodeStream(in);
				String userNameShort = userName;
				if(userName.length()>14)
					userNameShort = userName.substring(0, 13)+".."; 

				result[0]= new Result(tit,"User:"+userNameShort, sbL.toString(), 
						bitmap[0],sb.toString(),sbL.toString(),
						"http://www.flickr.com/photos/"+OWNER+"/"+ID+"/",null);
				result[0].setType(ResourceType.FLICKR);

				
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				return 0L;
			}
		}
		else if(idRicerca[0] == 1) //ricerca twitter
		{			
			try
			{
				URL urlTwitter;
				urlTwitter = new URL("https://api.twitter.com/1/statuses/show/"+param+".json");

				URLConnection connection = urlTwitter.openConnection();
				String line;
				StringBuilder builder = new StringBuilder();
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}

				String jSONString = builder.toString();

				JSONObject jObj = new JSONObject(jSONString);

				String text =  jObj.getString("text");
				String idStr =  jObj.getString("id_str");
				String fromUser = jObj.getJSONObject("user").getString("screen_name");
				String profileImageUrl =  jObj.getJSONObject("user").getString("profile_image_url");


				StringBuilder sbT = new StringBuilder();

				int lines = 1;
				int start = 0;
				int lineLenght = 10;
				int end = lineLenght;
				while((lines < 11)&&(end+1 < text.length()))
				{
					String analized = text.substring(start, end);
					int lastIndex = analized.lastIndexOf(' ');
					if(lastIndex == -1)
					{//caso in cui non ci sono spazi nella linea considerata
						sbT.append(text.substring(start, end));
						sbT.append('\n');
						start = end;
						end = end+lineLenght;
					}
					else
					{//caso in cui ci sono spazi nella linea considerata
						if(text.charAt(end) != ' ')
						{//se il primo carattere nella linea successiva non e' uno spazio 
							//vuol dire che la parola ci sta e quindi la mando a capo considerando l'index 
							sbT.append(text.substring(start, start+lastIndex));
							sbT.append(' ');
							sbT.append('\n');
							end = start+lastIndex + 1 + lineLenght;
							start = start+lastIndex + 1;
						}
						else
						{//se il primo carattere nella linea successiva e' uno spazio 
							//vuol dire che la parola ci sta e quindi la metto e vado avanti da dopo
							sbT.append(text.substring(start, end));
							sbT.append('\n');
							start = end+1;
							end = end+1+lineLenght;									
						}		
					}
					lines++;
				}

				if(text.length() - start > lineLenght)
				{
					sbT.append(text.substring(start, start+6));
					sbT.append("...");
				}
				else
				{
					sbT.append(text.substring(start, text.length()));
				}

				URL u = new URL(profileImageUrl);
				InputStream in = u.openConnection().getInputStream();

				bitmap[0] = BitmapFactory.decodeStream(in);

				String fromUserShort = fromUser;
				if(fromUser.length()>14)
					fromUserShort = fromUser.substring(0, 13)+".."; 

				result[0]= new Result(text,"User:"+fromUserShort, profileImageUrl, 
						bitmap[0],profileImageUrl,
						profileImageUrl,
						"https://mobile.twitter.com/"+fromUser+"/status/"+idStr,sbT.toString());
				result[0].setType(ResourceType.TWITTER);
			}

			catch (Exception e)
			{
				e.printStackTrace();
				return 0L;
			}			
		}
		else if(idRicerca[0] == 0)//gestione ricerca su youtube
		{
			URL urlThumb;
			InputStream in = null;

			URL url;

			try {
				
				url = new URL("http://gdata.youtube.com/feeds/api/videos/"+param+"?v=2&alt=jsonc");
				
				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpGet httpost = new HttpGet(url.toString());

				httpost.setHeader("Accept", "*/*");
				httpost.setHeader("Content-type", "application/json");

				ResponseHandler responseHandler = new BasicResponseHandler();
				String response = httpclient.execute(httpost, responseHandler);
				JSONObject jsonResponse = new JSONObject(response);
				
				String title = jsonResponse.getJSONObject("data").getString("title");
				
				String id = jsonResponse.getJSONObject("data").getString("id");
				String author = jsonResponse.getJSONObject("data").getString("uploader");
				String thumb = jsonResponse.getJSONObject("data").getJSONObject("thumbnail").getString("sqDefault");
				

				try {
					urlThumb = new URL(thumb);
					in = urlThumb.openConnection().getInputStream();
				} catch (Exception e) {
					e.printStackTrace();

				}
				bitmap[0] = BitmapFactory.decodeStream(in);

				String authorStrShort = author;
				if(author.length()>14)
					authorStrShort = author.substring(0, 13)+".."; 

				result[0]= new Result(title,"User:"+authorStrShort, id, bitmap[0],
						id,id,
						"http://www.youtube.com/watch?v="+id,null);
				result[0].setType(ResourceType.YOUTUBE);
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				return 0L;
			}
		}
		return 1L;	
	}

	protected void onProgressUpdate(Integer... progress) 
	{
		//g.myDialog.hide();	
		//progressBar = new ProgressDialog(g);
		//progressBar.setMessage("Level creation ...");
		//progressBar.show();
	}

	protected void onPostExecute(Long res) 
	{
		if(res == 1L)
		{
			//progressBar.hide();
			//progressBar.dismiss();
		}
		else if (res == 0L)
		{
			//errore
			//progressBar.hide();
			//progressBar.dismiss();
		}
	}
}